package cn.edu.zjut.mina.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.zjut.mina.service.IDownloadService;

@Service("downloadService")
public class DownloadServiceImpl implements IDownloadService {

	/**
	 * 文件下载
	 * @param userInfo
	 * @param filename 文件名
	 * @param request
	 * @param response
	 */
	@Transactional(rollbackFor=Exception.class)
	public void apkDownload(String userInfo,String filename,HttpServletRequest request,HttpServletResponse response){
	    InputStream in = this.getClass().getResourceAsStream("/fileDownload.properties");
		Properties pr = new Properties();
		String path = "";
		if(in==null)
			throw new RuntimeException("配置文件不存在！");
		try{
			pr.load(in);
		}catch(Exception e){
			throw new RuntimeException(e.getMessage());
		}
		path = pr.getProperty("path");

		path = path + "/"+filename;
		System.out.println("文件路径为："+path);
		File file = new File(path);
		if(!(file.exists() && file.canRead())) {
			System.out.println("文件不存在");
        }
		try{
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
		    byte[] buffer = new byte[fis.available()];
		    fis.read(buffer);
		    fis.close();
		    response.reset();
		    
		 // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
		    response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
		    response.addHeader("Content-Length", "" + file.length());
		    OutputStream os = new BufferedOutputStream(response.getOutputStream());
		    response.setContentType("application/octet-stream");
		    os.write(buffer);// 输出文件
		    os.flush();
		    os.close();

		}catch(IOException e){
			throw new RuntimeException(e.getMessage());
		}
	}
}
